<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\Video
 *
 * @property int $id
 * @property string|null $title
 * @property string $image
 * @property string|null $content
 * @property string|null $link
 * @property int $views
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read mixed $player
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereContent($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereImage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereLink($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Video whereViews($value)
 * @mixin \Eloquent
 */
class Video extends Model
{
    protected $table = 'video';
    protected $primaryKey = 'id';
    protected $fillable = ['title', 'content', 'image', 'link', 'views'];
    protected $appends = ['player'];

    /**
     * @param $value
     * @return string
     */
    public function getImageAttribute($value)
    {
        return $value ? image_url($value) : $value;
    }

    /**
     * @param $value
     */
    public function setImageAttribute($value)
    {
        $this->attributes['image'] = strip_image_url($value);
    }

    public function getPlayerAttribute()
    {
        $url = $this->link;
        preg_match('/(youku\.com|v\.qq\.com)/', strtolower($url), $matches);
        if (isset($matches[1])) {
            if ($matches[1] == 'youku.com') {
                preg_match('/id\_(\w+)[\=|\.html]/', $url, $urls);
                return '<iframe src="https://player.youku.com/embed/' . $urls[1] . '" frameborder="0" webkit-playsinline playsinline x5-playsinline x-webkit-airplay="allow" allowfullscreen></iframe>';
            }

            if ($matches[1] == 'v.qq.com') {
                preg_match('/\/([a-zA-Z0-9]+)\.html/', $url, $urls);
                return '<iframe frameborder="0" src="https://v.qq.com/txp/iframe/player.html?vid=' . $urls[1] . '" webkit-playsinline playsinline x5-playsinline x-webkit-airplay="allow" allowFullScreen="true"></iframe>';
            }

            return null;
        }

        return null;
    }
}
